package me.chan.chatting.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import me.chan.chatting.server.factory.GroupServiceFactory;
import me.chan.chatting.server.model.Group;
import me.chan.chatting.server.msg.GroupQuitRequestMessage;
import me.chan.chatting.server.msg.GroupQuitResponseMessage;

import java.util.Objects;

@Slf4j
@ChannelHandler.Sharable
public class GroupQuitInboundHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        Group group = GroupServiceFactory.getInstance().removeMember(msg.getGroupName(), msg.getUsername());
        if (Objects.isNull(group)) {
            ctx.writeAndFlush(new GroupQuitResponseMessage(false,
                                        "The group "+ msg.getGroupName() + " is not existed"));
            return ;
        }

        ctx.writeAndFlush(new GroupQuitResponseMessage(true,
                                "you have quit the group "+msg.getGroupName()));

    }
}
